#include "MainUI.h"


/*串口解析BUF & 接收索引*/
uint8_t MainUI::analysisBuf[MAX_ANALYSIS_LEN] = {0};    /*用于解析帧数据*/
uint16_t MainUI::analysisIndex = 0 ;


void MainUI::m_refreshSerialList()
{
    QStringList serialList;
    serialList.clear();
    ui->cboxSerialList->clear();
    
    QString firstItem;
    firstItem.clear();
    
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QString item = info.portName() + ":" + info.description() + " " + info.manufacturer();
        serialList.append(item);
        
        if(item.contains(QString("340")))
        {
            firstItem = item;
        }
    }
    
    /* 如果串口列表个数至少有一个*/
    if(serialList.count() >= 1)
    {
        ui->cboxSerialList->addItems(serialList);
    }

    /* 如果至少有一个CH430芯片*/
    if(!firstItem.isEmpty())
    {
        ui->cboxSerialList->setCurrentText(firstItem);
    }
}

void MainUI::on_serialReadyRead()
{
    QByteArray buf;
    buf.clear();
    
    buf = m_serial.readAll();
    
    if(!buf.isEmpty())
    {
        m_SerialRevBuf.append(buf);
    }
}

bool MainUI::m_comGetChar(char *ch, uint32_t port)
{
    Q_UNUSED(port);
    
    if(m_SerialRevBuf.size() > 0)
    {
        *ch = m_SerialRevBuf.at(0); /*取第一个字符*/
        m_SerialRevBuf.remove(0,1); /*删除第一个字符*/
        return true;
    }
    else
    {
        return false;
    }
}

void MainUI::m_comAnalysis()
{
    uint8_t ch = 0;
    
    /*帧结构*/
    static uint16_t frame_len = 0 ;
    static uint16_t tx_addr = 0 ;
    static uint16_t rx_addr = 0 ;
    static uint16_t main_sec = 0 ;
    static uint16_t sub_sec = 0 ;
    
    Q_UNUSED(frame_len);
    Q_UNUSED(tx_addr);
    Q_UNUSED(rx_addr);
    Q_UNUSED(main_sec);
    Q_UNUSED(sub_sec);
    
    while(m_comGetChar( (char*)(&ch) ))
    {
        //qDebug("%02X ",ch);
        
        analysisBuf[analysisIndex % MAX_ANALYSIS_LEN] = ch ;
        analysisIndex++;
        
        if(analysisIndex == 1)       /*前面2个是帧头*/
        {
            if(ch != 0xAA)
            {
                analysisIndex = 0 ;
            }
        }
        else if(analysisIndex == 2)  /*前面2个是帧头*/
        {
            if(ch != 0xAA)
            {
                analysisIndex = 0 ;
            }
        }
        else if(analysisIndex == 4)  /*帧长度*/
        {
            frame_len = ((analysisBuf[3] << 8) | analysisBuf[2]) & 0xFFFF;
            
            if(frame_len < MIN_ANALYSIS_LEN || frame_len > MAX_ANALYSIS_LEN)
            {
                m_crcChkErrDis();
                qDebug("err:frame_len %d",frame_len);
                analysisIndex = 0 ;
            }
            
        }
        else if(analysisIndex == 6)  /*帧长度 取反*/
        {
            uint16_t reverse = ((analysisBuf[5] << 8) | analysisBuf[4]) & 0xFFFF;
            
            /*这里 &0x00FF 非常有必要！！！*/
            if( ((~reverse)&0xFFFF) != frame_len )
            {
                m_crcChkErrDis();
                qDebug("err:reverse %04X",frame_len);
                analysisIndex = 0 ;
            }
            
        }
        else if(analysisIndex == 8)  /*发送方地址*/
        {
            tx_addr = ((analysisBuf[7] << 8) | analysisBuf[6]) & 0xFFFF;
            
        }
        else if(analysisIndex == 10)  /*接收方地址*/
        {
            rx_addr = ((analysisBuf[9] << 8) | analysisBuf[8]) & 0xFFFF;
            
        }
        else if(analysisIndex == 12)  /*主功能*/
        {
            main_sec = ((analysisBuf[11] << 8) | analysisBuf[10]) & 0xFFFF;
            
        }
        else if(analysisIndex == 14)  /*子功能*/
        {
            sub_sec = ((analysisBuf[13] << 8) | analysisBuf[12]) & 0xFFFF;
            
        }
        else if(analysisIndex >= MIN_ANALYSIS_LEN && analysisIndex >= frame_len)  /*一帧数据接收完毕了，这里的16很有灵性*/
        {
            uint16_t crc_ret = CRC16_CALC(analysisBuf,frame_len);
            static bool isTogglePixmap = true;
            
            if(crc_ret == 0)
            {
                m_mainSubSecDis(main_sec,sub_sec);
                m_comExexCmd();
                
                ui->lblToggle->setIcon(isTogglePixmap ? QIcon(":/image/heart_red.png"):QIcon(":/image/heart_blue.png"));
                isTogglePixmap = !isTogglePixmap;
                
                m_ptChkPassDis();
            }
            else
            {
                m_crcChkErrDis();
            }
            analysisIndex = 0 ;
        }
    }
}

void MainUI::m_crcChkErrDis()
{
    /*
     * 这是CRC错误次数一共有 3 个地方
     * 1：长度校验
     * 2：长度按位取反校验
     * 3：一阵数据收完CRC校验
    */
    
    /* 校验失败次数递增*/
    ++m_crcErrCnt;
    
    /* 显示校验失败次数*/
    ui->lcdNumberErrCnt->display(m_crcErrCnt);
}

void MainUI::m_ptChkPassDis()
{
    ++m_crcPassCnt;
    
    ui->lcdNumberCrcPassCnt->display(m_crcPassCnt);
}

void MainUI::m_mainSubSecDis(int main_sec , int sun_sec)
{
    setWindowTitle(TITLE_TEXT_WITH_FUN(main_sec,sun_sec));
}

void MainUI::m_comExexCmd()
{
    memset(&cmd_frame_rx,0,sizeof(CMD_FRAME));
    memcpy(&cmd_frame_rx,analysisBuf,sizeof(CMD_FRAME));
    
    if(cmd_frame_rx.main_sec == 7)
    {
        switch(cmd_frame_rx.sub_sec)
        {
        case 1:
        {
            ++m_revPtCnt; /* 接收到的总点数，递增，用作横坐标*/
            
            SERIE_LINE(1)->append(QPointF(m_revPtCnt, sin(m_revPtCnt)));

            m_slipAPt();
        }break;
            
        default: break;
        }
    }
}
